package com.baizhi.aspect;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.dao.CmfzLogDao;
import com.baizhi.entity.CmfzAdmin;
import com.baizhi.entity.CmfzLog;
import com.baizhi.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Configuration
public class LogAspect {

    @Autowired
    private CmfzLogDao cmfzLogDao;

    /**
     * 因为在增强中要获取注解的值  所以切注解 切LogAnnotation
     *
     *代表着只有添加注解的方法  才会被Aop
     * @param joinPoint
     */

    @After("@annotation(com.baizhi.annotation.LogAnnotation)")
    public  void  logAfter(JoinPoint joinPoint){
        /**
         *
         * 采集日志数据  封装到对象中
         */

        CmfzLog cmfzLog = new CmfzLog();
//  获取request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = requestAttributes.getRequest();
        CmfzAdmin admin = (CmfzAdmin) request.getSession().getAttribute("admin");
        if (admin != null){
            cmfzLog.setAdminId(admin.getId());
        }else {
//            添加0代表没有登录
            cmfzLog.setAdminId(0);
        }
        /**
         * 将日志数据  添加数据库
         *
         */
//        String addr = request.getRemoteAddr();
        String ip = IPKit.getIpAddrByRequest(request);
        cmfzLog.setLogIp(ip);

//            获取注解  通过切入点对象joinPoint 获取到方法的签名
//        通过方法签名对象获取到方法对象
//        通过方法对象获取方法上的注解
        MethodSignature signature= (MethodSignature) joinPoint.getSignature();

        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);

//        获取注解的值
        String content = annotation.content();
        String type = annotation.type();
        cmfzLog.setLogDate(new Date());
        cmfzLog.setLogContent(content);
        cmfzLog.setLogType(type);
        System.out.println(cmfzLog);
        cmfzLogDao.insert(cmfzLog);
    }
}
